//
//  HttpRequestOperation.m
//  httpCommon
//
//  Created by admin on 2017/8/10.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "HttpRequestOperation.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

#import <AFNetworking/AFNetworking.h>
#import <YYModel/YYModel.h>
#import <IBase/IBase.h>

#import "HttpRequestManager.h"
#import "HttpUploadManager.h"


@implementation HttpRequestOperation

static HttpRequestFaildBlock _block;

+ (void)setRequestFiladBlock:(HttpRequestFaildBlock)requestFiladBlock{
    _block = requestFiladBlock;
}

+ (HttpRequestFaildBlock)requestFiladBlock{
    return _block;
}


+ (NSString*)hostURL{
    return HostUrl.apiUrl;
}

+ (NSString*)resourceURL{
    return HostUrl.sourceUrl;
}

+ (void)setRequestHeader:(NSDictionary *)requestHeader{
    
    [[HttpRequestManager sharedInstance] setRequestHeader:requestHeader];
    
    [[HttpUploadManager sharedInstance] setRequestHeader:requestHeader];
}
    


#pragma mark - 通用：数据请求（请求数据为model）
+ (void)request:(HttpRequest *)request quite:(BOOL)quite callBack:(HttpResponseBlock)callBack{
    
    NSDictionary *parameters = [request params];
    
    NSString *url = [self allURL:HttpRequestOperation.hostURL method:[request action]];
#ifdef DEBUG
    NSLog(@"request:%@->parameters:%@", url, parameters);
#endif
    HttpMethod method = [request method];
    
    Class responseClass = [request responseClass];
    
    if ([url isEqualToString:@""]){
        if (callBack){
            HttpResponse* response = [responseClass new];
            response.message = @"网络请求地址配置错误";
            response.code = -1;
            response.data = nil;
            callBack(response);
        }
        return;
    }
    
    if(!quite){
        [Toast spin:nil];
    }
    
    [[HttpRequestManager sharedInstance] requestWithURL:url method:method params:parameters response:responseClass callback:^(HttpResponse * _Nonnull response) {
        
        if(!quite){
            [Toast hidden];
        }
        if(callBack){
            dispatch_async(dispatch_get_main_queue(), ^{
                callBack(response);
            });
        }
        
        [response failure:^(APIError * _Nonnull error) {
            [HttpRequestOperation setLogRestfulApiEventWithUrl:url erCode:response.code exMsg:error.errorInfo];
        }];
        
    }];
}


#pragma mark - 上传文件
+ (void)upload:(HttpRequest *)request files:(NSArray<HttpUploadFile *> *)files quite:(BOOL)quite callBack:(HttpResponseBlock)callBack
{
    if (files == nil){
        [self request:request quite:quite callBack:callBack];
        return;
    }
    
    NSDictionary *parameters = [request params];
    NSString *url = [self allURL:HttpRequestOperation.hostURL method:[request action]];
#ifdef DEBUG
    NSLog(@"Request:%@->parameters:%@", url, parameters);
#endif
    if (!url.length){
        if (callBack){
            HttpResponse* response = [HttpResponse new];
            response.message = @"网络请求地址配置错误";
            response.code = -1;
            response.data = nil;
            callBack(response);
        }
        return;
    }
    
    Class responseClass = [request responseClass];
    
    if(!quite){
        [Toast spin:nil];
    }
    
    [[HttpUploadManager sharedInstance] upload:url params:parameters fileConfigs:files response:responseClass callback:^(HttpResponse * _Nonnull response) {
        
        if(!quite){
            [Toast hidden];
        }
        
        if(callBack){
            dispatch_async(dispatch_get_main_queue(), ^{
                 callBack(response);
            });
        }
        [response failure:^(APIError * _Nonnull error) {
            [HttpRequestOperation setLogRestfulApiEventWithUrl:url erCode:response.code exMsg:error.errorInfo];
        }];
    }];
}

/**
 *  新地址普通文件上传
 */
+ (void)uploadFile:(HttpRequest*)request files:(NSArray<HttpUploadFile *> *)files quite:(BOOL)quite callBack:(HttpResponseBlock)callBack{
    if (files == nil){
        [self request:request quite:quite callBack:callBack];
        return;
    }
    
    NSDictionary *parameters = [request params];
    NSString *url = [self allURL:HttpRequestOperation.resourceURL method:[request action]];
#ifdef DEBUG
    NSLog(@"Request:%@->parameters:%@", url, parameters);
#endif
    if (!url.length){
        if (callBack){
            HttpResponse* response = [HttpResponse new];
            response.message = @"网络请求地址配置错误";
            response.code = -1;
            response.data = nil;
            callBack(response);
        }
        return;
    }
    
    Class responseClass = [request responseClass];
    
    if(!quite){
        [Toast spin:nil];
    }
    
    [[HttpUploadManager sharedInstance] upload:url params:parameters fileConfigs:files response:responseClass callback:^(HttpResponse * _Nonnull response) {
        
        if(!quite){
            [Toast hidden];
        }
        
        if(callBack){
            dispatch_async(dispatch_get_main_queue(), ^{
                callBack(response);
            });
        }
        [response failure:^(APIError * _Nonnull error) {
            [HttpRequestOperation setLogRestfulApiEventWithUrl:url erCode:response.code exMsg:error.errorInfo];
        }];
    }];
}

/**
 *  新地址文件安全上传
 */
+ (void)safeUpload:(HttpRequest*)request files:(NSArray<HttpUploadFile *> *)files quite:(BOOL)quite callBack:(HttpResponseBlock)callBack{
    
    if (files == nil){
        [self request:request quite:quite callBack:callBack];
        return;
    }
    
    NSDictionary *parameters = [request params];
    NSString *url = [self allURL:HttpRequestOperation.resourceURL method:[request action]];
#ifdef DEBUG
    NSLog(@"Request:%@->parameters:%@", url, parameters);
#endif
    if (!url.length){
        if (callBack){
            HttpResponse* response = [HttpResponse new];
            response.message = @"网络请求地址配置错误";
            response.code = -1;
            response.data = nil;
            callBack(response);
        }
        return;
    }
    
    Class responseClass = [request responseClass];
    
    if(!quite){
        [Toast spin:nil];
    }
    
    [[HttpUploadManager sharedInstance] upload:url params:parameters fileConfigs:files response:responseClass callback:^(HttpResponse * _Nonnull response) {
        
        if(!quite){
            [Toast hidden];
        }
        
        if(callBack){
            dispatch_async(dispatch_get_main_queue(), ^{
                callBack(response);
            });
        }
        [response failure:^(APIError * _Nonnull error) {
            [HttpRequestOperation setLogRestfulApiEventWithUrl:url erCode:response.code exMsg:error.errorInfo];
        }];
    }];
}


/**
 全地址
 */
+ (NSString *)allURL:(NSString *)baseURL method:(NSString *)method{
    
    if([method hasPrefix:@"http"])
        return method;
    
    NSString* url = [NSString stringWithFormat:@"%@%@",baseURL,method];
    
    return url;
}

#pragma mark - 监听网络状态
+ (void)startMonitoringWithResult:(void(^)(BOOL invalid))block;
{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        BOOL invalid = NO;
        switch (status){
                case AFNetworkReachabilityStatusReachableViaWWAN:
                case AFNetworkReachabilityStatusReachableViaWiFi:
                invalid = YES;
                break;
            default:
                invalid = NO;
                break;
        }
        block(invalid);
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

+ (void)stopMonitoring{
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}


#pragma mark - log
+ (void)setLogRestfulApiEventWithUrl:(NSString *)url erCode:(NSInteger)erCode exMsg:(NSString *)exMsg
{
    if(HttpRequestOperation.requestFiladBlock){
        HttpRequestOperation.requestFiladBlock(url, erCode, exMsg);
    }
}

@end
